package com.houtai.authority;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 权限认证拦截器
 *
 */
public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {
	private RedisTemplate redisTemplate;
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 请求处理完成之后
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		// 处理器执行完毕之后
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod hm = (HandlerMethod) handler;

			Class<?> clazz = hm.getBeanType();
			Method m = hm.getMethod();
			try {
				if (clazz != null && m != null) {
					boolean isClzAnnotation = clazz.isAnnotationPresent(Authority.class);
					boolean isMethondAnnotation = m.isAnnotationPresent(Authority.class);
					Authority authority = null;
					// 如果方法和类声明中同时存在这个注解，那么方法中的会覆盖类中的设定。
					if (isMethondAnnotation) {
						authority = m.getAnnotation(Authority.class);
					} else if (isClzAnnotation) {
						authority = clazz.getAnnotation(Authority.class);
					}

					if (authority != null) {
						if (AuthorityType.NoValidate == authority.value()) {
							return true;
						}  else if(AuthorityType.Login == authority.value()) {

							// 不验证权限，验证是否登录
							if(request.getParameter("token") == null ){

								//跳转
								String url = "/v5/back/manager/login";
								response.getWriter().write("<script>top.location.href='"
										+ url + "'</script>");

								return false;
							} else {
								if (redisTemplate.opsForValue().get(request.getParameter("token")) == null) {

									String url = "/v5/back/manager/login";
									response.getWriter().write("<script>top.location.href='"
											+ url + "'</script>");
									return false;
								}
							}
						}
					}
					return true;
				}
			} catch (Exception e) {
			}
		}
		return false;
	}

	public void setRedisTemplate(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
}
